<template>
	<pd-popup ref="popup">
		<view class="__pd_select __common_popup_wrapper">
			<view class="__pd_options">
				<view 
					class="__pd_option flex jcsb aic"
					v-for="item in options" 
					:key="item[propsConfig.id]" 
					@tap="selectHandler(item)">
					<text>{{item[propsConfig.label]}}</text>
					<text class="iconfont primary-color" v-if="selectValue.includes(item[propsConfig.id])">&#xe62c;</text>
				</view>
			</view>
			<view class="__pd_select_footer flex aic">
				<button type="default" @tap="cancelHandler">取 消</button>
				<button type="primary" @tap="confirmHandler" :disabled="!selectValue.length">确 定</button>
			</view>
		</view>
	</pd-popup>
</template>

<script setup lang="ts">
import { useCompRef } from '../hooks/useRefs';
import type { TsHelp } from '../libs/ts-help';
import PdPopup from './pd-popup.vue';

const props = withDefaults(defineProps<{
	multiple: boolean,//是否多选
	propsConfig : {
		label: string,
		id: string
	}
}>(), {
	multiple: false,
	propsConfig : () => {
		return {
			label: 'label',
			id: 'id'
		};
	}
});

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options = ref<any[]>([]);
const multiple = ref(false);//是否允许多选

const popup = useCompRef(PdPopup);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let resolver : TsHelp.PromiseResolver<{value : any}>;
let rejecter : () => void;

type Ops = {
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	options : any[],
	multiple ?: boolean
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const open = (config : Ops) : Promise<{value : any}> => {
	return new Promise((r,j) => {
		options.value = config.options;
		(config.multiple !== undefined) && (multiple.value = config.multiple);
		resolver = r;
		rejecter = j;
		popup.value?.open();
	});
};

const selectValue = ref<Array<typeof options.value[number]['id']>>([]);
const selectHandler = (item : typeof options.value[0]) => {
	if(props.multiple) {
		selectValue.value = selectValue.value.concat(item[props.propsConfig.id]);
	} else {
		selectValue.value = [item[props.propsConfig.id]];
	};
};

const confirmHandler = () => {
	resolver && resolver({
		value : options.value.filter(v => selectValue.value.includes(v[props.propsConfig.id]))
	});
	popup.value?.close();
};

const cancelHandler = () => {
	rejecter && rejecter();
	popup.value?.close();
};

defineExpose({
	open
});

</script>

<style scoped lang="less">
.__pd_select {
	background: #fff;
	border-radius: 16rpx 16rpx 0 0;
	.__pd_options {
		max-height: 60vh;
		overflow-y: auto;
	}
	.__pd_option {
		padding: 30rpx;
		font-size: 30rpx;
		border-bottom: 1px solid #f1f1f1;
	}
	.__pd_select_footer {
		gap : 32rpx;
		margin-top: 32rpx;
		button {
			flex: 1;
		}
	}
}
</style>